package org.zn.note.mybatis.util;

import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.zn.note.mybatis.mapper.CmMerchantMapper;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @ClassName MyBatisUtils
 * @Author zn
 * @Date 2020/3/30 10:17
 **/
public class MyBatisUtils {

    public static final boolean DEBUG = false;

    // SqlSessionFactory 建议 全局作用域，一个数据(一套配置)对应一个单例就可以
    private static SqlSessionFactory sqlSessionFactory = MyBatisUtils.createSqlSessionFactoryByXml();

    // // SqlSession 建议 请求作用域或方法作用域，用后要close，线程不安全
    public static SqlSession openSession() {
        return sqlSessionFactory.openSession();
    }

    public static SqlSessionFactory createSqlSessionFactoryByXml() {
        return createSqlSessionFactoryByXml("mybatis/mybatis-config.xml");
    }

    // 创建SqlSessionFactory：XML方式
    public static SqlSessionFactory createSqlSessionFactoryByXml(String config) {
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(config);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

    // 创建SqlSessionFactory：Java方式
    public static SqlSessionFactory createSqlSessionFactoryByJava() {
        DataSource dataSource = getDataSource();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(CmMerchantMapper.class);
        return new SqlSessionFactoryBuilder().build(configuration);
    }

    private static DataSource getDataSource() {
        Properties properties = new Properties();
        properties.setProperty("driver", "com.mysql.jdbc.Driver");
        properties.setProperty("url", "jdbc:mysql://127.0.0.1:3306/mybatis");
        properties.setProperty("username", "root");
        properties.setProperty("password", "root");
        PooledDataSourceFactory pooledDataSourceFactory = new PooledDataSourceFactory();
        pooledDataSourceFactory.setProperties(properties);
        DataSource dataSource = pooledDataSourceFactory.getDataSource();
        return dataSource;
    }
}
